package com.atguigu.tingshu.search.config;

import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author: hy
 * @date:2025/9/4
 * @description:
 */
@Component
public class ThreadPoolExecutorConfig {

    //自定义线程池
    @Bean
    public ThreadPoolExecutor threadPoolExecutor() {
        //自定义线程池;因为使用工具类创建的线程池，要么是阻塞队列，要么是最大线程个数默认是：INTEGER.MAX_VALUE(21亿) 造成OOM

        int cpuCoreNum = Runtime.getRuntime().availableProcessors();
        System.out.println("cpu核心数：" + cpuCoreNum);
        return new ThreadPoolExecutor(
                cpuCoreNum,//核心线程数 业务需求：io=2n cpu=n+1
                cpuCoreNum * 2,//最大线程数
                3,//空闲线程存活时间
                TimeUnit.SECONDS,//时间单位
                new ArrayBlockingQueue<>(100),//阻塞队列
                Executors.defaultThreadFactory(),//线程工厂
                new ThreadPoolExecutor.AbortPolicy()//拒绝策略
        );
    }
}
